/*
* 1videoConference -- An open source video conferencing platform.
*
* Copyright (C) 2007 - 2008, Adiance Technologies Pvt. Ltd.
*
* Hardik Sanghvi <hardik.sanghvi @adiance.com>
*
* See http://www.1videoconference.org for more information about
* the 1videoConference project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, forums and mailing lists
* for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Threading;

namespace Adiance.VMukti.BAL
{
    public class ThreadedServiceHoster
    {
        const int SleepTime = 100;
        private ServiceHost m_serviceHost = null;
        private Thread m_thread;
        private string m_serviceAddress;
        Type SClass, SInterface;
        private bool m_running;
        private NetTcpBinding m_binding;

        public ThreadedServiceHoster(string serviceAddress, NetTcpBinding binding,Type ServerClass,Type ServerInterface)
        {
            m_binding = binding;
            m_serviceAddress = serviceAddress;
            SClass = ServerClass;
            SInterface = ServerInterface;
            m_thread = new Thread(new ThreadStart(ThreadMethod));
            m_thread.Start();
        }

        void ThreadMethod()
        {
            try
            {
                m_running = true;

                // Start the host
                m_serviceHost = new ServiceHost(SClass);
                m_serviceHost.AddServiceEndpoint(SInterface, m_binding, m_serviceAddress);
                m_serviceHost.Open();

                while (m_running)
                {
                    // Wait until thread is stopped
                    Thread.Sleep(SleepTime);
                }

                m_serviceHost.Close();
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "Adiance.VMukti.BAL--:--ThreadedServiceHoster.cs--:--ThreadMethod()--:----:--");
                Adiance.VMukti.BAL.clsUtility.LogException = exp;
                //System.Windows.MessageBox.Show("ThreadMethod"+exp.Message);
                if (m_serviceHost != null)
                {
                    m_serviceHost.Close();
                }

            }
        }

        /// <summary>
        /// Request the end of the thread method.
        /// </summary>
        public void Stop()
        {
            lock (this)
            {
                m_running = false;
            }
        }
    }

}
